package com.auoem.radio.recorder;
// [XD80A] play record file inividually, 2021.10.22 start

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

//import org.apache.http.util.ByteArrayBuffer;
// [XD80A] play record file inividually, 2021.10.22 end

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;

import com.auctus.am.framework.utils.LogM;
//import android.media.AudioSystem;

//import com.mediatek.storage.StorageManagerEx;

//import mobile.miki.VUMeterForAudioRecord;

public class AudioRecordUtils {

    private final static String TAG = "AudioRecordUtils";

    private static final int FREQUENCY = 44100;
    private static final int CHANNELCONFIGURATION = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    private static final int AUDIOENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private int mRecordBufSize;
    private AudioRecord mAudioRecord;
    private AudioTrack mAudioTrack;
    // [XD80A] play record file inividually, 2021.10.22 start
    private RecordThread mRecordThread;
    private PlayThread mPlayThread;
    public boolean isRecording = false;// 是否录放的标记
    public boolean isPlaying = false;// 是否播放
    //private static final String FILE_PATH = "/sdcard/Android/data/test_pcm.pcm";
    private static final String FILE_PATH = "/storage/emulated/0/Recording";
    private static final String FILE_NAME = "test_pcm.pcm";
    private com.auoem.radio.Recorder.AudioRecordCallBack callBack;

    public enum MICTYPE {
        RRESET_MIC, MAIN_MIC, SUB_MIC
    }
    // [XD80A] play record file inividually, 2021.10.22 end

    private String getMicType(MICTYPE type) {
        String t = "SET_MIC_CHOOSE=0";
        switch (type) {
            case RRESET_MIC:
                break;
            case MAIN_MIC:
                t = "SET_MIC_CHOOSE=1";
                break;
            case SUB_MIC:
                t = "SET_MIC_CHOOSE=2";
                break;
            default:

                break;
        }
        return t;
    }

    // [XD80A] play record file inividually, 2021.10.22 start
    @SuppressLint("MissingPermission")
    public AudioRecordUtils(com.auoem.radio.Recorder.AudioRecordCallBack callBack, MICTYPE type) {
        this.callBack = callBack;
//		AudioSystem.setParameters(getMicType(type));//dual mic
        mRecordBufSize = AudioRecord.getMinBufferSize(FREQUENCY,
                CHANNELCONFIGURATION, AUDIOENCODING);
//        mAudioRecord = new AudioRecord(
//                MediaRecorder.AudioSource.VOICE_COMMUNICATION/* 这个主意修改 */,
//                FREQUENCY, CHANNELCONFIGURATION, AUDIOENCODING, mRecordBufSize);
        mAudioRecord = new AudioRecord(
                MediaRecorder.AudioSource.VOICE_COMMUNICATION/* 这个主意修改 */,
                FREQUENCY, CHANNELCONFIGURATION, AUDIOENCODING, mRecordBufSize);
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, FREQUENCY,
                CHANNELCONFIGURATION, AUDIOENCODING,
                AudioTrack.getMinBufferSize(FREQUENCY, CHANNELCONFIGURATION,
                        AUDIOENCODING), AudioTrack.MODE_STREAM);
        mAudioTrack.setStereoVolume(1.0f, 1.0f);
        //mAudioTrack.setStereoVolume(0.1f, 0.1f);
        LogM.d(TAG, "AudioRecordUtils init final");
    }

    // [XD80A] play record file inividually, 2021.10.22 start
    @SuppressLint("MissingPermission")
    public AudioRecordUtils() {
        this.callBack = callBack;
//        AudioSystem.setParameters(getMicType(type));//dual mic
        mRecordBufSize = AudioRecord.getMinBufferSize(FREQUENCY,
                CHANNELCONFIGURATION, AUDIOENCODING);
        mAudioRecord = new AudioRecord(
                MediaRecorder.AudioSource.VOICE_COMMUNICATION/* 这个主意修改 */,
                FREQUENCY, CHANNELCONFIGURATION, AUDIOENCODING, mRecordBufSize);
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, FREQUENCY,
                CHANNELCONFIGURATION, AUDIOENCODING,
                AudioTrack.getMinBufferSize(FREQUENCY, CHANNELCONFIGURATION,
                        AUDIOENCODING), AudioTrack.MODE_STREAM);
        mAudioTrack.setStereoVolume(1.0f, 1.0f);
        //mAudioTrack.setStereoVolume(0.1f, 0.1f);
        LogM.d(TAG, "AudioRecordUtils init final");
    }

    public void startMic(boolean isStart) {
        if (isStart) {
            mAudioRecord.startRecording();// 开始录制
        } else {
            mAudioTrack.stop();
        }
    }

    // [XD80A] play record file inividually, 2021.10.22 end
    // [XD80A] play record file inividually, 2021.10.22 start
    public void startRecord() {

        isRecording = true;
        isPlaying = false;
        mRecordThread = new RecordThread();
        mRecordThread.start();

    }

    public void startPlay() {
        isRecording = false;
        isPlaying = true;
        mPlayThread = new PlayThread();
        mPlayThread.start();
    }


    public void resetState() {
        isRecording = false;
        isPlaying = false;
    }


    class RecordThread extends Thread {
        public void run() {
            try {
                byte[] buffer = new byte[mRecordBufSize];
                if (mPlayThread != null) {
                    mPlayThread.interrupt();
                    mPlayThread = null;
                }
                mAudioRecord.startRecording();// 开始录制
                File file = new File(FILE_PATH);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File mSampleFile = new File(file, FILE_NAME);
                if (mSampleFile.exists()) {
                    mSampleFile.delete();
                }
                mSampleFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(mSampleFile);
                while (isRecording) {
                    int bufferReadResult = mAudioRecord.read(buffer, 0,
                            mRecordBufSize);
                    fos.write(buffer);
                    long v = 0;
                    for (int i = 0; i < buffer.length; i++) {
                        v += buffer[i] * buffer[i];
                    }
                    double mean = v / (double) bufferReadResult;
                    double volume = 0.1 * Math.log10(mean);
                    volume = volume > 0.3 ? volume : 0;
//                    VUMeterForAudioRecord.VOLUME = volume;

                }
                mAudioRecord.stop();
                mAudioTrack.stop();
                fos.flush();
                fos.close();
//                VUMeterForAudioRecord.VOLUME = 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class PlayThread extends Thread {
        public void run() {
            try {
                Thread.sleep(300);
                if (mRecordThread != null) {
                    mRecordThread.interrupt();
                    mRecordThread = null;
                }
                File file = new File(FILE_PATH);
                File mSampleFile = new File(file, FILE_NAME);
                if (!mSampleFile.exists())
                    return;
                mAudioTrack.play();
                FileInputStream fis = new FileInputStream(mSampleFile);
                byte[] buffer = new byte[mRecordBufSize];

                while (fis.available() > 0 && isPlaying) {
                    int read = fis.read(buffer);
                    if (read == AudioTrack.ERROR_INVALID_OPERATION
                            || read == AudioTrack.ERROR_BAD_VALUE) {
                        continue;
                    }
                    if (read != -1 || read != 0) {
                        mAudioTrack.write(buffer, 0, read);
                    }
                }
                fis.close();
                mAudioTrack.stop();
                isPlaying = false;
                callBack.playFinish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    // [XD80A] play record file inividually, 2021.10.22 end
}
